import React, { Component } from "react";
import { connect } from "dva";
import { formatMessage, FormattedMessage } from "umi-plugin-react/locale";
import Link from "umi/link";
import { Checkbox, Alert, Icon, Input, Tabs, Form, Button } from "antd";
import Login from "@/components/Login";
import styles from "./Login.less";
import CryptoJS from "crypto-js";
import qywxLogo from "@/assets/qywx.png";
import lockPng from "@/assets/lock.png";
import banner from "@/assets/loginBanner.png";
import { getSystemPlatformInfo } from "@/services/platformManagement";
import jsonDataUtils from "@/utils/jsonDataUtils";
import MultiUserSelection from "./MultiUserSelection";

const { TabPane } = Tabs;
const { Tab, UserName, Password, Mobile, Captcha, Submit } = Login;
const isShowVerificationCode = true; //是否显示验证码

@connect(({ login, loading }) => ({
	login,
	submitting: loading.effects["login/login"],
}))
class LoginPage extends Component {
	state = {
		type: "account",
		autoLogin: true,
		randomNum: null,
		codeNum: "",
		isSaveLogin: false,
		activeKey: 1,
		loading: true,
		isShowQywxLogin: 2,
		// isShowQywxLogin: 4,
		platformInfo: {},
    showPart:"",
    tenantList:[]
	};

	componentDidMount() {
		const { location: { query } } = this.props;
		if (isShowVerificationCode) {
			this.getRandomNumber(8);
		};
		if (query.code) {
			this.loginByQywx(query.code);
		};
		this.getPlatformInfo();
    if(query.param){
      this.setState({
        showPart:"sso"
      },() => {
        this.ssoLogin(query.param)
      })
    }else{
      this.setState({
        showPart:'login'
      })
    }

    
	}

	getPlatformInfo = async () => {
		const res = await getSystemPlatformInfo();
		this.setState({ platformInfo: res })
	}

	loginByQywx = (code) => {
		const { dispatch } = this.props;
		dispatch({
			type: "login/loginByQywx",
			payload: { code },
		});
	};

	getRandomNumber = (n) => {
		let num = "";
		for (let i = 0; i < n; i++) {
			num += Math.floor(Math.random() * 10);
		};
		this.setState({ randomNum: num });
	};

	onTabChange = (type) => {
		this.setState({ type });
	};

	onGetCaptcha = () =>
		new Promise((resolve, reject) => {
			this.loginForm.validateFields(["mobile"], {}, (err, values) => {
				if (err) {
					reject(err);
				} else {
					const { dispatch } = this.props;
					dispatch({ type: "login/getCaptcha", payload: values.mobile, }).then(resolve).catch(reject);
				}
			});
		});

	handleSubmit = (err, values) => {
		const { type, randomNum, codeNum, isSaveLogin } = this.state;
		let obj = values;
		if (isShowVerificationCode) {
			obj.key = randomNum;
			obj.code = parseInt(codeNum);
		};
		obj.isSaveLogin = isSaveLogin;
		if (!err) {
			const { dispatch } = this.props;
			const encryptParam = this.encrypt(JSON.stringify(values));
			dispatch({
				type: "login/login",
				payload: { data: encryptParam },
				callback: (res) => {
          console.log('登录的回调===',res);
					this.getRandomNumber(8);
          if(Array.isArray(res)){
            this.setState({
              showPart:"userSelect",
              tenantList:res
            })
          }
				},
			});
		}
	};

	changeAutoLogin = (e) => {
		this.setState({ autoLogin: e.target.checked });
	};

	renderMessage = (content) => (
		<Alert style={{ marginBottom: 24 }} message={content} type='error' showIcon />
	);

	changeCodeNum = (e) => {
		this.setState({ codeNum: e.target.value });
	};

	changeImage = () => {
		this.getRandomNumber(8);
	};

	changeIsSaveLogin = (e) => {
		this.setState({ isSaveLogin: e.target.checked });
	};

	encrypt(encryptString) {
		var PUBLIC_KEY = "biaopin123456789";
		var key = CryptoJS.enc.Utf8.parse(PUBLIC_KEY);
		var srcs = CryptoJS.enc.Utf8.parse(encryptString);
		var encrypted = CryptoJS.AES.encrypt(srcs, key, {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7,
		});
		return encrypted.toString();
	}

	handleTabsChange = (key) => {
		// console.log(key);
		this.setState({ activeKey: key }, () => {
			if (key == 2) {
				this.appendJs();
			}
		});
	};

	appendJs = () => {
		const script = document.createElement("script");
		script.src = "http://wwcdn.weixin.qq.com/node/wework/wwopen/js/wwLogin-1.2.4.js";
		document.body.appendChild(script);

		setTimeout(function () {
			const url = window.location.href;
			const redirect_url = `https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=${window.appid}&agentid=${window.agentid}&redirect_uri=${url}&state=STATE`;
			let wwLogin = new WwLogin({
				id: "wx_reg", // 登录页面显示二维码的容器id
				appid: window.appid, // 企业微信的CorpID，在企业微信管理端查看
				agentid: window.agentid, // 授权方的网页应用id，在具体的网页应用中查看
				redirect_uri: encodeURIComponent(url), // 重定向的地址，需要进行encode
				state: new Date().getTime(),
				href: "", // 自定义样式链接，只支持https协议的资源地址
			});
		}, 500);
	};

	regSubmit = () => {
		this.props.form.validateFields((err, values) => {
			if (!err) {
				// console.log('-----------------', values);
			}
		})
	}

  toLoginItem = data => {
    const { dispatch } = this.props;
    dispatch({
      type: "login/loginToTenant",
      payload: {
        id:data.id,
        username:data.name,
        tenantId:data.tenantId,
        type:data.type,
        path:data.path,
        nick:data.nick
      },
      callback: (res) => {
        console.log('选择租户后的回调',res);
        
      },
    });
  }

  ssoLogin = param => {
    const { dispatch } = this.props;
    dispatch({
      type: "login/loginBySSO",
      payload: { param },
      callback: (res) => {
        console.log('sso的回调===',res);
        if(Array.isArray(res)){
          this.setState({
            showPart:"userSelect",
            tenantList:res
          })
        }
      },
    });
  }

	render() {
		const { login, submitting } = this.props;
		const { getFieldDecorator } = this.props.form;
		const { type, autoLogin, randomNum, isSaveLogin, activeKey, loading, isShowQywxLogin, platformInfo,showPart,tenantList } = this.state;
		let isLogin = () => {
			switch (isShowQywxLogin) {
				case 1:
					return (
						<div>
							<div className={styles.robotTitle}>
								<img src={qywxLogo} alt='' />
								企业微信扫码登录
							</div>
							<div id='wx_reg' style={{ textAlign: "center", minHeight: 405 }}></div>
							{/* <div className={styles.qywxLogin} onClick={() => this.setState({ isShowQywxLogin: 2 })}>
								<img src={lockPng} alt='' />
								账号密码登录
							</div> */}
						</div>
					);

				case 2:
					return (
						<Login defaultActiveKey={type} onTabChange={this.onTabChange} onSubmit={this.handleSubmit} ref={form => this.loginForm = form}>
							<div className={styles.robotTitle}>
								<img src={lockPng} alt='' />
								账号密码登录
							</div>
							<div className={styles.loginForm}>
								{login.code && login.type === "account" && !submitting && this.renderMessage(
									formatMessage({ id: "app.login.message-invalid-credentials", })
								)}
								<label className={styles.formLabel}>账号</label>
								<UserName
									name='username'
									placeholder='请输入登录账号'
									rules={[
										{
											required: true,
											message: formatMessage({ id: "validation.userName.required", }),
										},
									]}
								/>
								{/* <label className={styles.formLabel}>Email</label>
								<UserName
									name='username'
									placeholder='请输入邮箱Email'
									rules={[
										{
											required: true,
											message: formatMessage({ id: 'validation.email.required', }),
										},
									]}
								/> */}
								<label className={styles.formLabel}>密码</label>
								<Password
									name='password'
									placeholder='请输入登录密码'
									rules={[
										{
											required: true,
											message: formatMessage({ id: "validation.password.required", }),
										},
									]}
									onPressEnter={(e) => {
										e.preventDefault();
										this.loginForm.validateFields(this.handleSubmit);
									}}
								/>
								<div>
									{isShowVerificationCode ? (
										<div>
											<label className={styles.formLabel} style={{ display: "block", marginBottom: 10 }}>验证码</label>
											<div style={{ display: "flex" }}>
												<Input
													placeholder={"请输入验证码"}
													style={{
														width: "64%",
														height: 40,
														backgroundColor: "#ffffff",
														color: "#000000",
													}}
													prefix={<Icon type="safety-certificate" theme="filled" />}
													onChange={this.changeCodeNum}
													type={"number"}
													maxLength={3}
												/>
												{randomNum ? (
													<img
														src={"/cloud/number.jpg?key=" + randomNum}
														style={{
															width: "calc(36% - 10px)",
															marginLeft: 10,
															cursor: "pointer",
															height: 40,
														}}
														onClick={this.changeImage}
													/>
												) : (
													""
												)}
											</div>
										</div>
									) : (
										""
									)}
								</div>
								<div style={{ marginTop: 10, display: 'none' }}>
									<Checkbox onChange={this.changeIsSaveLogin} checked={isSaveLogin} style={{ color: "#333" }}>记住账号</Checkbox>
								</div>
								<Submit loading={submitting} style={{ marginTop: 10 }}>
									<FormattedMessage id='app.login.login' />
								</Submit>
								{/* <div style={{ textAlign: 'center', cursor: 'pointer' }} onClick={() => this.setState({ isShowQywxLogin: 3 })}>补充账号信息</div> */}
							</div>

							{/*
                			<div
								style={{ padding: '0px 28px 32px', color: '#48CFF6' }}
								onClick={() => {
									this.setState({ isShowQywxLogin: 4 }, () => {
										// this.appendJs();
									});
								}}
							>
								<span style={{ cursor: 'pointer' }}>手机验证码登录</span>
							</div>
              				<div
								className={styles.qywxLogin}
								onClick={() => {
									this.setState({ isShowQywxLogin: 1 }, () => {
										this.appendJs();
									});
								}}
							>
								<img src={qywxLogo} alt='' />
								企业微信扫码登录
							</div> */}
						</Login>
					);

				case 3:
					return (
						<div>
							<div className={styles.robotTitle}>请补充账号信息</div>
							<Form layout="vertical" style={{ padding: '24px' }}>
								<Form.Item label="用户名">
									{getFieldDecorator('username', {
										rules: [{ required: true, message: '请输入用户名' }],
									})(<Input />)}
								</Form.Item>
								<Form.Item label="密码">
									{getFieldDecorator('password', {
										rules: [{ required: true, message: '密码至少8个字符，含有数字和字母' }],
									})(<Input />)}
								</Form.Item>
								<Form.Item label="确认密码">
									{getFieldDecorator('oldPassword', {
										rules: [{ required: true, message: '两次输入的密码必须一致' }],
									})(<Input />)}
								</Form.Item>
								<Form.Item label="手机号码">
									{getFieldDecorator('phone', {
										rules: [{ required: true, message: '请输入正确的手机号码' }],
									})(<Input />)}
								</Form.Item>
								<Form.Item label="短信验证码">
									<div style={{ display: 'flex', justifyContent: 'space-between' }}>
										{getFieldDecorator('smsCode', {
											rules: [{ required: true, message: '请输入正确的验证码' }],
										})(<Input style={{ width: "64%" }} />)}
										<Button type="primary" style={{ width: "calc(36% - 10px)" }}>获取验证码</Button>
									</div>
								</Form.Item>
								<Form.Item>
									<Button type="primary" block onClick={this.regSubmit}>确认</Button>
									<div style={{ textAlign: 'center', cursor: 'pointer', marginTop: 10 }} onClick={() => this.setState({ isShowQywxLogin: 2 })}>登录</div>
								</Form.Item>
							</Form>
						</div>
					);

				case 4:
					return (
						<Login
							defaultActiveKey={type}
							onTabChange={this.onTabChange}
							onSubmit={this.handleSubmit}
							ref={form => this.loginForm = form}
						>
							<div className={styles.robotTitle} style={{ padding: '20px 0' }}>验证码登录</div>
							<div className={styles.loginForm}>
								<label className={styles.formLabel}>手机号码</label>
								<UserName
									name='username'
									placeholder='请输入手机号码'
									rules={[
										{
											required: true,
											message: formatMessage({ id: 'validation.phone-number.required', }),
										},
									]}
								/>
								<div>
									{isShowVerificationCode ? (
										<div>
											<label className={styles.formLabel} style={{ display: "block", marginBottom: 10 }}>验证码</label>
											<div style={{ display: "flex" }}>
												<Input
													placeholder={"请输入验证码"}
													style={{
														width: "64%",
														height: 40,
														backgroundColor: "#ffffff",
														color: "#000000",
													}}
													prefix={
														<Icon type="safety-certificate" theme="filled" />
													}
													onChange={this.changeCodeNum}
													type={"number"}
													maxLength={3}
												/>

												<div id='smsCode' style={{ width: "calc(36% - 10px)", marginLeft: 10, cursor: "pointer", lineHeight: '38px', }}>
													<Button style={{ height: 36 }} className={styles.smsCode}>发送验证码</Button>
												</div>
												{/* {randomNum ? (
													<img
														src={"/cloud/number.jpg?key=" + randomNum}
														style={{
															width: "calc(36% - 10px)",
															marginLeft: 10,
															cursor: "pointer",
															height: 40,
														}}
														onClick={this.changeImage}
													/>
												) : (
													""
												)} */}
											</div>
										</div>
									) : (
										""
									)}
								</div>
								<Submit loading={submitting} style={{ marginTop: 10 }}>
									<FormattedMessage id='app.login.login' />
								</Submit>
							</div>
							<div
								style={{ padding: '0px 28px 32px', color: '#48CFF6' }}
								onClick={() => {
									this.setState({ isShowQywxLogin: 2 }, () => {
										// this.appendJs();
									});
								}}
							>
								<span style={{ cursor: 'pointer' }}>密码登录</span>
							</div>
						</Login>
					)
			}
		}

		return (
      
        showPart == 'login' ? (
          <div>
            <div className={styles.banner}>
              <img src={platformInfo && platformInfo.advertiseUrl ? `${fileUrl + platformInfo.advertiseUrl}` : banner} alt='' style={{ width: 662, height: 604 }} />
            </div>
            <div className={isShowQywxLogin === 3 ? styles.mainReg : styles.main}>
              <div className={styles.loginBox}>{isLogin()}</div>
            </div>
          </div>
        ) : showPart == 'userSelect' ? (
          <MultiUserSelection tenantList={tenantList} toLoginItem={this.toLoginItem} />
        ) : (
          <div></div>
        )
      
		);
	}
}

export default Form.create()(LoginPage);
